package chapter18.h18_4;

import java.io.*;

public class Main {
    public static final String SAVEFILENAME = "game.dat";
    public static void main(String[] args){
        Gamer gamer = new Gamer(100);
        Memento memento = loadMemento();
        if(memento != null){
            System.out.println("读取上次保存文档开始游戏");
            gamer.restoreMemento(memento);
        }else{
            System.out.println("新游戏");
            memento = gamer.createMemento();
        }
        for(int i = 0; i < 100; i++){
            System.out.println("====" + i);
            System.out.println("当前的状态：" + gamer);
            gamer.bet();
            System.out.println("所有金钱为：" + gamer.getMoney() );
            if(gamer.getMoney() > memento.getMoney()){
                System.out.println("金钱增加，保存状态");
                memento = gamer.createMemento();
                saveMemento(memento);
            }else if(gamer.getMoney() < memento.getMoney() / 2){
                System.out.println("金钱减少很多，回复之前状态");
                gamer.restoreMemento(memento);
            }

            try{
                Thread.sleep(100);
            }catch (Exception e){
                e.printStackTrace();
            }
            System.out.println("");
        }
    }

    public static void saveMemento(Memento memento){
        try{
            ObjectOutput out = new ObjectOutputStream(new FileOutputStream(SAVEFILENAME));
            out.writeObject(memento);
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static Memento loadMemento(){
        Memento memento = null;
        try{
            ObjectInput in= new ObjectInputStream(new FileInputStream(SAVEFILENAME));
            memento = (Memento) in.readObject();
            in.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return memento;
    }
}
